/**
 * @Author: 陈瑞鹏
 * @Date:   2021-11-08 19:19:24
 * @Last Modified by:   陈瑞鹏
 * @Last Modified time: 2022-12-05 17:49:23
 */
import { Proxy } from "../pureMvc/patterns/proxy/Proxy";
import { connect } from './socket.io.1.4.8.js';
import { Dictionary } from "../core/Dictionary";

export default class SocketManager extends Proxy {

    private static _instance: SocketManager = null;

    public static ins() {

        if (this._instance == null) {

            this._instance = new SocketManager();
        }

        return this._instance;
    }

    public socket: any = null;

    public sendDic: Dictionary<string, boolean> = new Dictionary();

    public jiemi(cb, data) {

        let t = new Promise((resolve, reject) => {
            this.ab2str(data, (e) => {
                // resolve(e);
                cb(e);
            })
        })
    }

    public ab2str(u, f) {

        var b = new Blob([u]);
        var r = new FileReader();
        r.readAsText(b, 'utf-8');
        r.onload = function () {
            if (f) f.call(null, r.result)
        }
    }

    public initSocket() {

    }

    /**
     * 
     * @param e 
     * @param data 
     */
    public onLevelDown(e: any, data: any) {

        // console.log(e);
    }

    /**
     * 监听连接 
     */
    public onConnect(e: any, data: any) {

        // console.log('连接成功!')
        // console.log(e);
    }

    /**
     * 错误监听
     * @param e 
     */
    public onError(e) {

        // console.log("错误:", e)

    }

    /**
     * 消息监听
     * @param e 
     */
    public onMessage(e) {

        e = JSON.parse(e);

    }

    /**
     * 退出
     */
    public onExit(e) {

        // console.log("退出:", e)

    }



    /**
     * 发送信息
     */
    public sendMessage(name: string = "", data: any) {

        // if (this.sendDic.get(name)) {
        //     return;
        // }else {
        //     this.sendDic.set(name, true);
        // }

        if (!this.socket) return;

        this.socket.emit(name, data);
    }
}